import 'dart:convert';

import 'package:get/get.dart';

import '../values/values.dart';
import 'services.dart';

class UserStore extends GetxController {
  static UserStore get to => Get.find();

  // 是否登录
  final _isLogin = false.obs;

  bool get isLogin => _isLogin.value;

  // 用户 profile
  final _profile = UserLoginResponseEntity().obs;

  UserLoginResponseEntity get profile => _profile.value;

  bool get hasToken => _profile.value.token?.isNotEmpty ?? false;

  @override
  void onInit() {
    super.onInit();
    var profileOffline = StorageService.to.getString(STORAGE_USER_PROFILE_KEY);
    if (profileOffline.isNotEmpty) {
      _profile(UserLoginResponseEntity.fromJson(jsonDecode(profileOffline)));
      _isLogin.value = true;
    }
  }

  // 保存 profile
  Future<void> saveProfile(UserLoginResponseEntity profile) async {
    _isLogin.value = true;
    _profile.value = profile;
    StorageService.to.setString(STORAGE_USER_PROFILE_KEY, jsonEncode(profile));
  }

  // 注销
  Future<void> onLogout() async {
    await StorageService.to.remove(STORAGE_USER_PROFILE_KEY);
    _profile.value = UserLoginResponseEntity();
    _isLogin.value = false;
  }
}

class UserLoginResponseEntity {
  String? id;
  String? token;
  String? avatar;
  String? nickName;
  String? email;
  String? mobile;
  String? mobileType;
  int? gender;
  String? inviteCode;
  int? level;

  UserLoginResponseEntity({
    this.id,
    this.token,
    this.avatar,
    this.nickName,
    this.email,
    this.mobile,
    this.mobileType,
    this.gender,
    this.inviteCode,
    this.level,
  });

  factory UserLoginResponseEntity.fromJson(Map<String, dynamic> json) => UserLoginResponseEntity(
        id: json["id"],
        token: json["token"],
        avatar: json["avatar"],
        nickName: json["nickName"],
        email: json["email"],
        mobile: json["mobile"],
        mobileType: json["mobileType"],
        gender: json["gender"],
        inviteCode: json["inviteCode"],
        level: json["level"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "token": token,
        "avatar": avatar,
        "nickName": nickName,
        "email": email,
        "mobile": mobile,
        "mobileType": mobileType,
        "gender": gender,
        "inviteCode": inviteCode,
        "level": level,
      };
}
